'use strict';

/**
 * Created by twer on 15/3/6.
 */
angular.module('photo')
    .controller('PhotoListCtrl', [
        '$scope',
        '$rootScope',
        'PageConstant',
        'PathSuffixConstant',
        'PhotoListService',
        'AlbumService',
        '$routeParams',
        'PhotoHost',
        'PhotoSliderModalService',
        'PhotoCollection',
        'PhotoService',
        function ($scope, $rootScope, PageConstant, PathSuffixConstant, PhotoListService, AlbumService, $routeParams, PhotoHost, PhotoSliderModalService, PhotoCollection, PhotoService) {
            $rootScope.visitedUserId = $routeParams.userId;
            var albumId = $routeParams.albumId;

            $scope.query = function (pageNumber) {
                var queryCondition = {
                    offset: (pageNumber - 1) * PageConstant.countPerPage,
                    countPerPage: PageConstant.countPerPage,
                    albumId: albumId
                };

                PhotoListService.query(queryCondition, function (response) {
                    var photoCollection = new PhotoCollection(response);
                    $scope.photos = photoCollection.photos;
                    $scope.totalCount = photoCollection.totalCount;
                });
            };

            $scope.showSlider = function (index) {
                PhotoSliderModalService.activate({photoIndex: index});
            };

            $scope.remove = function (photo) {
                if (!confirm('是否要删除' + photo.title + '？')) {
                    return;
                }

                PhotoService.remove({photoId: photo._id}, function () {
                    alert('删除成功！');
                    var newPhotos = [];
                    angular.forEach($scope.photos, function (p) {
                        if (p._id != photo._id) {
                            newPhotos.push(p);
                        }
                    });
                    $scope.photos = newPhotos;
                    $scope.totalCount = $scope.totalCount - 1;
                });
            };

            $scope.album = AlbumService.query({albumId: albumId + PathSuffixConstant});
            $scope.query(1);
        }])

    .controller('PhotoNewCtrl', [
        '$scope',
        '$rootScope',
        '$routeParams',
        'AlbumListService',
        'PathSuffixConstant',
        'FileService',
        'ImageTypes',
        'PhotoService',
        'flowFactory',
        function ($scope, $rootScope, $routeParams, AlbumListService, PathSuffixConstant, FileService, ImageTypes, PhotoService, flowFactory) {
            $rootScope.visitedUserId = $routeParams.userId;
            $scope.newPhoto = {};

            var visitedUserId = $routeParams.userId;

            $scope.initialize = function () {
                var queryCondition = {
                    offset: 0,
                    countPerPage: 100,
                    ownerId: visitedUserId + PathSuffixConstant
                };

                $scope.albums = $scope.albums || {};
                AlbumListService.query(queryCondition, function (response) {
                    $scope.albums = response.results;
                });
            };

            $scope.photoFlow = flowFactory.create();
            $scope.uploadFiles = [];

            $scope.uploadStart = function () {
                if (!$scope.newPhoto.album) {
                    alert('请选择相册！');
                    return;
                }
                $scope.photoFlow.upload();
            };

            $scope.uploadSuccess = function (file, message) {
                var result = angular.fromJson(message).result[0];
                $scope.uploadFiles.push({
                    fileId: result.id,
                    author: {identity: visitedUserId},
                    albumId: $scope.newPhoto.album._id,
                    title: photoTitle(result.filename)
                });
            };

            $scope.uploadComplete = function () {
                PhotoService.save({}, $scope.uploadFiles, function () {
                    alert('照片上传成功！');
                    $scope.uploadFiles = [];
                });
            };

            function photoTitle(fileName) {
                return fileName.substring(0, fileName.lastIndexOf('.'));
            }

            $scope.initialize();
        }])

    .controller('PhotoSliderCtrl', [
        '$scope',
        '$routeParams',
        'PhotoSliderModalService',
        'PhotoListService',
        'AlbumService',
        'PhotoCollection',
        function ($scope, $routeParams, PhotoSliderModalService, PhotoListService, AlbumService, PhotoCollection) {
            var albumId = $routeParams.albumId;
            $scope.close = PhotoSliderModalService.deactivate;

            $scope.query = function () {
                var queryCondition = {
                    offset: 0,
                    countPerPage: 1000,
                    albumId: albumId
                };

                PhotoListService.query(queryCondition, function (response) {
                    $scope.photos = new PhotoCollection(response).photos;
                    $scope.$broadcast('PhotoListReturned', $scope.photos);

                    $scope.photoSlides = [];
                    angular.forEach($scope.photos, function (photo) {
                        $scope.photoSlides.push(photo.uri);
                    });
                });
            };

            $scope.afterSlide = function (index) {
                $scope.$broadcast("SlidedEvent", $scope.photos[index]);
            };

            $scope.query();
            $scope.album = AlbumService.query({albumId: albumId});
        }])

    .controller('PhotoCommentsCtrl', [
        '$scope',
        '$rootScope',
        'CommentQueryService',
        'CommentModifyService',
        'ProfilePhotoService',
        'PhotoHost',
        function ($scope, $rootScope, CommentQueryService, CommentModifyService, ProfilePhotoService, PhotoHost) {
            $scope.newComment = {
                content: ''
            };

            $scope.$on('PhotoListReturned', function (e, photos) {
                $scope.currentPhotoId = photos[$scope.photoIndex]._id;
                $scope.query();
            });

            $scope.$on('SlidedEvent', function (e, photo) {
                $scope.currentPhotoId = photo._id;
                $scope.query();
            });

            /**
             * 加载所有的评论
             */
            $scope.query = function () {
                if (!$scope.currentPhotoId) {
                    return;
                }
                CommentQueryService.query({hostId: $scope.currentPhotoId, type: 'photo'}, function (response) {
                    $scope.comments = response.results || [];
                    console.log($scope.comments);
                    setPhotosUri($scope.comments);
                });
            };

            /**
             * 添加评论
             */
            $scope.add = function () {
                if ($scope.newComment.content == '') {
                    alert('请录入评论内容！');
                    return;
                }
                $scope.newComment.referenceId = $scope.currentPhotoId;
                $scope.newComment.author = {identity: $rootScope.currentUser.id, name: $rootScope.currentUser.name};
                $scope.newComment.commentType = 'photo';

                CommentModifyService.add($scope.newComment, function (response) {
                    var createdComment = $scope.newComment;
                    createdComment._id = response._id;
                    createdComment.createTime = {$date: new Date()};
                    ProfilePhotoService.query({userId: createdComment.author.identity}, function (response) {
                        createdComment.author.photoUri = PhotoHost + 'cdrmimg/' + response.photoId + '?w=50&h=50';
                    });

                    $scope.comments.push(createdComment);
                    $scope.newComment = {content: ''};
                });
            };

            function setPhotosUri(objectList) {
                angular.forEach(objectList, function (object) {
                    ProfilePhotoService.query({userId: object.author.identity}, function (response) {
                        object.author.photoUri = PhotoHost + 'cdrmimg/' + response.photoId + '?w=50&h=50';
                    });
                });
            }
        }]);

